package com.example.yrdev.ordering_system.Report;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.yrdev.ordering_system.Common.CommonActivity;
import com.example.yrdev.ordering_system.Database.DingHanDB;
import com.example.yrdev.ordering_system.Database.PurchasedItemTB;
import com.example.yrdev.ordering_system.Database.RefundGoodTB;
import com.example.yrdev.ordering_system.Model.CardRecord;
import com.example.yrdev.ordering_system.Model.CustomViewHolder;
import com.example.yrdev.ordering_system.Model.Operator;
import com.example.yrdev.ordering_system.Model.PurchaseReport;
import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.http.HttpClient;
import com.example.yrdev.ordering_system.http.HttpResponseHandler;
import com.example.yrdev.ordering_system.http.NetWorkConstant;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by luke on 10/17/16.
 */

public class RefundCommodityActivity extends CommonActivity {

    @InjectView(R.id.payMode)RadioGroup payMode;
    @InjectView(R.id.report_list)ListView reportList;
    @InjectView(R.id.report_container)HorizontalScrollView report_container;

    int purchase_mode=3;
    Context context;
    ArrayList<HashMap>hashMapArrayList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context=RefundCommodityActivity.this;
        refundedItemList=RefundGoodTB.getAllRefundItemBaseOnType(context,purchase_mode);

    initView();

    }
    ArrayList<RefundGoodTB.Item>refundedItemList;
    int http_paymode=8;

    public void initView(){
        hashMapArrayList=new ArrayList<>();

        setContentView(R.layout.refund_commodity_layout);
        ButterKnife.inject(this);
        setBarTitle(GlobalFunction.getResourceString(this,R.string.refund_detail));
        showBackButton();

        payMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton selectedRadioButton=(RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());

                if (i==R.id.cash){

                    purchase_mode=0;
                    http_paymode=9;

                }else {

                    purchase_mode=3;
                    http_paymode=8;

                }

           refundedItemList=RefundGoodTB.getAllRefundItemBaseOnType(context,purchase_mode);

                resetOptionView(selectedRadioButton);

                initReport();

            }

        });


        showRightButtonWithListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                uploadReport();

            }
        },"上传");
        initReport();

    }

    private  void uploadReport(){

        if (refundedItemList.size()>0)

           uploadRefundReport();

        else
            GlobalFunction.ToastAlert(this,"无记录可上传");


    }
    private  void   uploadRefundReport(){

        for (RefundGoodTB.Item refundItem: refundedItemList){



            if (refundItem.getUploadMark()==0){
                String vipCardID="";

                RefundGoodTB.Item report=refundItem;
                if (purchase_mode==3)
                    vipCardID=report.getCard_ID();


                HashMap<String,String> itemParam=new HashMap<>();
                itemParam.put("ticketID",report.getItem_TicketID());
                itemParam.put("commodityID",report.getItem_ID());
                itemParam.put("volume",String.valueOf(report.getPurchaseVolume()));
                itemParam.put("primeCost",report.getPrimeCost());
                itemParam.put("saleCost",String.valueOf(report.getSaleCost()));
                itemParam.put("cost",String.valueOf(report.getTotalPrice()));
                itemParam.put("restoredNum",String.valueOf(report.getRestoredNum()));
                itemParam.put("discount",report.getDiscountRate());
                itemParam.put("dateTime",report.getHttpDateTime());
                  itemParam.put("employeeID", Operator.getIntance().getEmployeeID());
                  itemParam.put("vipCardID",vipCardID);
                  itemParam.put("payMode",String.valueOf(http_paymode));




                //  CardRecord.changeCardReportUploadMark(this,respRecord);

                hashMapArrayList.add(itemParam);


            }




        }

        GlobalFunction.printTextByTag(hashMapArrayList+"");
        if (hashMapArrayList.size()>0){
            GlobalFunction.ToastAlert(this,"正在上传");
            HashMap<String,Object>body=new HashMap<>();
            body.put("num",String.valueOf(hashMapArrayList.size()));
            body.put("item",hashMapArrayList);



            HttpClient.postWithFunction(NetWorkConstant.HTTP_uploadPurchaseRecord,body,new HttpResponseHandler(){
                @Override
                protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                    super.handleSuccessMessage(statusCode, headers, responseBody);
                    JSONObject jsonObject;
                    try {
                        jsonObject = new JSONObject(responseBody);
                        String resp=jsonObject.getString("response");

                        JSONObject respResponse=new JSONObject(resp);
                        String head=respResponse.getString("head");

                        JSONObject respHead=new JSONObject(head);
                        String respCode=respHead.getString("respCode");
                        GlobalFunction.printTextByTag(responseBody);
                        if (respCode.equals("0000")){

                            GlobalFunction.ToastAlert(RefundCommodityActivity.this,"上传成功");
                            customAdapter.notifyDataSetChanged();


                          changeUploadMark();


                            //initializeListData();

                        }else {

                            GlobalFunction.ToastAlert(RefundCommodityActivity.this,"上传失败");
                        }

                    }catch (Exception e){


                    }


                }

                @Override
                protected void handleFailureMessage(Request request, IOException e) {
                    super.handleFailureMessage(request, e);
                }
            });

        }else {

            GlobalFunction.ToastAlert(this,"已把所有记录上传");

        }



    }
    private  void changeUploadMark(){
        for (RefundGoodTB.Item report: refundedItemList){



            if (report.getUploadMark()==0){
                report.setUploadMark(1);




                RefundGoodTB.changeRefundReportUploadMark(this,report);

            }




        }
    }
    CustomAdapter customAdapter;


    public void initReport(){

    if (refundedItemList==null||refundedItemList.size()==0){

        report_container.setVisibility(View.GONE);

    }else {

        report_container.setVisibility(View.VISIBLE);
    customAdapter =new CustomAdapter(context,refundedItemList);
        reportList.setAdapter(customAdapter);

       }


    }

    public void resetOptionView(RadioButton selectedButton){
        for (int i=0;i<payMode.getChildCount();i++){
            RadioButton radioButton=(RadioButton)payMode.getChildAt(i);
            radioButton.setBackgroundColor(Color.parseColor("#b8d3ee"));
            radioButton.setTextColor(Color.parseColor("#c7c7c7"));

        }
        selectedButton.setBackgroundColor(Color.parseColor("#FF1B469A"));
        selectedButton.setTextColor(Color.parseColor("#FFFFFF"));
    }



public static class CustomAdapter extends BaseAdapter{
        Context context;
       ArrayList<RefundGoodTB.Item>arrayList;

    CustomAdapter(Context context, ArrayList<RefundGoodTB.Item> itemArrayList){

        this.context=context;
        this.arrayList=itemArrayList;

    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return arrayList.get(i);

    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        LayoutInflater inflater=LayoutInflater.from(context);
        RefundGoodTB.Item goods=arrayList.get(i);

        if (view==null){

          view=inflater.inflate(R.layout.refund_commodity_detail_row,null);
            CustomViewHolder viewHolder=new CustomViewHolder();
            viewHolder.setIndex((TextView)view.findViewById(R.id.index));
            viewHolder.setTick((ImageView)view.findViewById(R.id.tick));
            viewHolder.setGoods_ticketID((TextView)view.findViewById(R.id.goods_ticketID));
            viewHolder.setGoods_code((TextView)view.findViewById(R.id.goods_code));
            viewHolder.setGoods_name((TextView)view.findViewById(R.id.goods_name));
            viewHolder.setGoods_purchDate((TextView)view.findViewById(R.id.goods_PurchaseDate));
            viewHolder.setGoods_refundDate((TextView)view.findViewById(R.id.goods_refundDate));
            viewHolder.setGoods_amount((TextView)view.findViewById(R.id.goods_amount));
            viewHolder.setGood_RetailPrice((TextView)view.findViewById(R.id.goods_retail_price));
            viewHolder.setGood_totalPrice((TextView)view.findViewById(R.id.goods_totalPrice));

            view.setTag(viewHolder);

        }




        CustomViewHolder viewHolder=(CustomViewHolder)view.getTag();
        viewHolder.getIndex().setText(i+1+"");
        if (goods.getUploadMark()==0){

            viewHolder.getTick().setVisibility(View.GONE);

        }else {

            viewHolder.getTick().setVisibility(View.VISIBLE);
        }
        viewHolder.getGoods_ticketID().setText(goods.getItem_TicketID());
        viewHolder.getGoods_code().setText(goods.getItem_ID());
        viewHolder.getGoods_name().setText(goods.getItem_name());
        viewHolder.getGoods_purchDate().setText(goods.getItem_purchDate());
        viewHolder.getGoods_refundDate().setText(goods.getItem_refundDate());
        viewHolder.getGoods_amount().setText(String.valueOf(goods.getItem_amount()));
        viewHolder.getGood_RetailPrice().setText(String.valueOf(goods.getSaleCost())+"元");
        viewHolder.getGood_totalPrice().setText(String.valueOf(goods.getTotalPrice())+"元");

//        int temp=goods.getItem_amount();
//
//        if (temp==0){
//            viewHolder.getGood_refundCount().setText("-");
//
//        }else if(temp<goods.getPurchaseVolume()){
//
//            viewHolder.getGood_refundCount().setText(temp+"");
//
//        }
//        else {
//
//            viewHolder.getGood_refundCount().setText("全部");
//
//        }



        return view;

    }
}

}
